const app = getApp();
var wxParse = require('../../../wxParse/wxParse.js');
var time = require("../../../utils/util.js");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    prompt: '',
    is_load: 0,
    default_img: {},
    detail_id: 0,
    current_time: 0,
    //轮播图属性
    imgUrls: [{
      pic_cover_mid: '/images/common/default_goods.png'
    }],
    autoplay: true,
    interval: 3000,
    duration: 300,
    circular: true,
    indicatorColor: '#AAA',
    indicatorActiveColor: '#FF0036',
    swiper_height: 375,
    selectType: 'img',
    goodsChildNav: 0,
    //遮罩层
    mask_show: 0,
    //优惠券弹框
    popup_show: 0,
    //商家服务弹框
    service_show: 0,
    //拼团弹框
    spelling_show: 0,
    spelling_index: 0,
    //购买、购物车弹框
    sBuy: 0,
    //阶梯优惠弹框
    ladder_preferential_show: 0,
    // 分享选择弹框
    share_show: 0,
    // 分享海报弹框
    poster_show: 0,
    poster_img: '',
    animation: '',
    goods_id: 0,
    sku_pic: {
      src: '',
      img_list: '',
    },
    is_share: 0,
    show_price: 0,
    buyButtonStatus: 0, // 购买、购物车确认按钮
    goods_info: {
      goods_name: '加载中...',
      shipping_fee: 0,
      sales: 0,
      clicks: 0,
      goods_type: 0,
    }, // 商品详情
    spelling: {}, // 选中拼团
    comments_list: [], // 评价列表
    comments_type: 0, // 评价类型
    spec_list: [], // 规格列表
    attr_value_items_format: '', // 选中规格组
    sku_id: 0, // 选中规格
    spec_id: [],
    spec_value_id: [], // spu value ID
    attr_value_items: [], //规格组
    sku_info: {}, // 选中规格信息
    stock: 0, // 选中规格库存
    member_price: 0.00, // 选中规格价格
    buy_num: 1, // 购买数量
    group_id: 0, // 拼团ID
    pintuan_list: [],
    bargain_id: 0, //砍价ID
    receiver_mobile: '', // 砍价收货人手机号
    distribution_type: 'logistics',
    shop_name: '',
    from_type: '',
    save_img_open_type: '',
    addCartFlag: 0,
    comboFlag: 0,
    comboPackagesFlag: 0,
    buyNextFlag: 0,
    goodsDetailFlag: 0,
    moreEvaluationFlag: 0,
    groupPurchaseFlag: 0,
    groupBookingFlag: 0,
    confirmSpellFlag: 0,
    pointExchangeFlag: 0,
    goodsPresellFlag: 0,
    toReceivePopupFlag: 0,
    bargainNextFlag: 0,
    bargainFlag: 0,
    address_show: 0,
    promotion_type: 0,
    goods_attr_show: 0, //商品属性弹框
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    let window_width = wx.getSystemInfoSync().windowWidth;
    let shop_name = app.globalData.title;
    let goods_id = 0;
    let from_type = '';
    let sku_id = 0;
    let bargain_id = 0;
    let group_id = 0;

    //扫二维码进入
    if (options.scene) {
      let param = app.checkEmpty(options.scene, '');
      let param_array = param.split('|');

      for (let index in param_array) {
        if (param_array[index].indexOf('goods_id') == 0) {
          // 商品ID
          goods_id = param_array[index].split('-')[1];
        } else if (param_array[index].indexOf('source_uid') == 0) {
          //source ID
          let sourceid = param_array[index].split('-')[1];
          sourceid = isNaN(parseInt(sourceid)) ? '' : parseInt(sourceid);
          app.setSourceId(sourceid);
        }
      }
    }

    app.webSiteInfo(that);
    let web_site_info = that.data.web_site_info;
    if (web_site_info != undefined && web_site_info.title != '' && web_site_info.title != undefined) {
      shop_name = web_site_info.title;
    }

    if (options.goods_id && options.goods_id != undefined && options.goods_id != '') {
      goods_id = options.goods_id
    }

    if (app.checkEmpty(options.goods_name, '') != '') {
      wx.setNavigationBarTitle({
        title: options.goods_name
      })
    }

    if (options.group_id && options.group_id != undefined) {
      group_id = options.group_id;
    }

    if (options.bargain_id && options.bargain_id != undefined) {
      bargain_id = options.bargain_id;
    }

    if (options.sku_id && options.sku_id != undefined) {
      sku_id = options.sku_id;
    }

    if (options.from_type && options.from_type != undefined) {
      from_type = options.from_type;
    }

    that.setData({
      goods_id: goods_id,
      sku_id: sku_id,
      group_id: group_id,
      shop_name: shop_name,
      bargain_id: bargain_id,
      from_type: from_type
    })
    // 版权信息
    app.copyRightLoad(that);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this;

    app.restStatus(that, 'comboFlag');
    app.restStatus(that, 'comboPackagesFlag');
    app.restStatus(that, 'buyNextFlag');
    app.restStatus(that, 'goodsDetailFlag');
    app.restStatus(that, 'moreEvaluationFlag');
    app.restStatus(that, 'groupPurchaseFlag');
    app.restStatus(that, 'groupBookingFlag');
    app.restStatus(that, 'confirmSpellFlag');
    app.restStatus(that, 'pointExchangeFlag');
    app.restStatus(that, 'goodsPresellFlag');
    app.restStatus(that, 'bargainNextFlag');
    app.restStatus(that, 'bargainFlag');
    app.restStatus(that, 'toReceivePopupFlag');
    // 默认图
    app.defaultImg(that, true);
    // 登录状态
    app.getMemberId(that);

    wx.getSetting({
      success: function(res) {
        if (res.authSetting['scope.writePhotosAlbum'] === false) {
          that.setData({
            save_img_open_type: 'openSetting'
          })
        } else if (res.authSetting['scope.writePhotosAlbum'] === true) {
          that.setData({
            save_img_open_type: ''
          })
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    app.clearTimer(this)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    app.clearTimer(this)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(options) {
    let that = this;
    let goods_info = that.data.goods_info;
    let sku_info = that.data.sku_info;
    let sku_pic = that.data.sku_pic;
    let default_img = that.data.default_img;
    let uid = app.checkEmpty(app.globalData.uid, 0);

    sku_info.sku_name = app.checkEmpty(sku_info.sku_name, '');
    sku_pic.img_list = app.checkEmpty(sku_pic.img_list, []);
    sku_pic.img_list[0] = app.checkEmpty(sku_pic.img_list[0], '');
    goods_info.img_list = app.checkEmpty(goods_info.img_list, []);
    goods_info.img_list[0] = app.checkEmpty(goods_info.img_list[0], {});
    goods_info.img_list[0].pic_cover_small = app.checkEmpty(goods_info.img_list[0].pic_cover_small, '');
    let img = sku_pic.img_list[0] == "" ? goods_info.img_list[0].pic_cover_small : sku_pic.img_list[0];
    img = img == "" ? default_img.value.default_goods_img : img;

    let path = '/pages/goods/goodsdetail/goodsdetail?goods_id=' + goods_info.goods_id + '&goods_name=' + goods_info.goods_name;

    if (uid > 0) {
      path = '/pages/goods/goodsdetail/goodsdetail?goods_id=' + goods_info.goods_id + '&source_uid=' + uid + '&goods_name=' + goods_info.goods_name;
    }

    return {
      title: goods_info.goods_name + ' ' + sku_info.sku_name,
      path: path,
      imageUrl: img
    }
  },

  /**
   * 加载商品信息
   */
  loadInfo: function() {
    let that = this;
    let goods_id = that.data.goods_id;
    let sku_id = that.data.sku_id;
    let group_id = that.data.group_id;
    let detail_id = that.data.detail_id;
    let attr_value_items_format = '';
    let member_price = 0.00;
    let bargain_id = that.data.bargain_id

    app.sendRequest({
      url: 'System.Goods.goodsDetail',
      data: {
        goods_id: goods_id,
        sku_id: sku_id,
        group_id: group_id,
        bargain_id: bargain_id,
      },
      success: function(res) {
        console.log(res);
        let code = res.code;
        let data = res.data;
        if (code == 0) {
          try {
            let goods_info = data.goods_detail;
            if (goods_info.description != '' && goods_info.description != null && goods_info.description != undefined) {
              detail_id = goods_id;
            }
            // 价格初始化
            let show_price = parseFloat(goods_info.promotion_price) < parseFloat(goods_info.member_price) ? goods_info.promotion_price : goods_info.member_price;

            // 商品单位初始化
            goods_info.have_unit = 1;
            if (goods_info.goods_unit == undefined || goods_info.goods_unit == null || goods_info.goods_unit == '') {
              goods_info.goods_unit = '件';
              goods_info.have_unit = 0;
            }

            //购买数量初始化
            let buy_num = that.data.buy_num;
            if (parseInt(goods_info.min_buy) > 0) {
              buy_num = parseInt(goods_info.min_buy);
            }

            //优惠券时间格式转换
            for (let i in goods_info.goods_coupon_list) {
              if (goods_info.goods_coupon_list[i].term_of_validity_type == 0) {
                goods_info.goods_coupon_list[i].start_time = time.formatTime(goods_info.goods_coupon_list[i].start_time, 'Y.M.D');
                goods_info.goods_coupon_list[i].end_time = time.formatTime(goods_info.goods_coupon_list[i].end_time, 'Y.M.D');
              }
            }

            //预售发货时间格式转换
            if (goods_info.is_open_presell == 1 && goods_info.presell_distribution_type == 1) {
              goods_info.presell_time = time.formatTime(goods_info.presell_time, 'Y-M-D h:m:s');
            }

            //视频路径处理
            goods_info.goods_video_address = goods_info.goods_video_address == undefined ? '' : goods_info.goods_video_address;
            goods_info.goods_video_address = goods_info.goods_video_address == 0 ? '' : goods_info.goods_video_address;
            goods_info.goods_video_address = app.VIDEO(goods_info.goods_video_address);

            //商品图片处理
            let imgUrls = goods_info.img_list;
            for (let index in imgUrls) {
              imgUrls[index].pic_cover_micro = app.IMG(imgUrls[index].pic_cover_micro);
              imgUrls[index].pic_cover_small = app.IMG(imgUrls[index].pic_cover_small);
              imgUrls[index].pic_cover_mid = app.IMG(imgUrls[index].pic_cover_mid);
              imgUrls[index].pic_cover_big = app.IMG(imgUrls[index].pic_cover_big);
              if (index == 0 && app.checkEmpty(imgUrls[index].pic_cover_mid, '') != '') {
                app.getWindowSize(that, true, imgUrls[index].pic_cover_mid);
              }
            }

            //组合商品图片处理
            let main_goods = app.checkEmpty(goods_info.promotion_detail.combo_package, [])
            for (let index in main_goods.data) {
              let img = main_goods.data[index].main_goods.pic_cover_mid;
              let comb_goods_array = app.checkEmpty(goods_info.promotion_detail.combo_package.data[index].goods_array, [])
              for (let key in comb_goods_array) {
                let img = goods_info.promotion_detail.combo_package.data[index].goods_array[key].pic_cover_mid;
                goods_info.promotion_detail.combo_package.data[index].goods_array[key].pic_cover_mid = app.IMG(img);
              }
              goods_info.promotion_detail.combo_package.data[index].main_goods.pic_cover_mid = app.IMG(img);
            }

            //拼团头像处理
            if (goods_info.goods_pintuan != undefined) {
              goods_info.point_exchange_type = 0;
              if (goods_info.goods_pintuan.pintuan_list != undefined) {
                for (let index in goods_info.goods_pintuan.pintuan_list.data) {
                  let img = goods_info.goods_pintuan.pintuan_list.data[index].group_user_head_img;
                  goods_info.goods_pintuan.pintuan_list.data[index].group_user_head_img = app.IMG(img);
                }
              }
            }

            //富文本格式转化
            let description = goods_info.description;
            wxParse.wxParse('description', 'html', description, that, 5);

            // 评论默认值
            goods_info.evaluates_count = {};
            goods_info.evaluates_count.evaluate_count = 0;
            goods_info.evaluates_count.imgs_count = 0;
            goods_info.evaluates_count.praise_count = 0;
            goods_info.evaluates_count.center_count = 0;
            goods_info.evaluates_count.bad_count = 0;

            let promotion_detail = app.checkEmpty(goods_info.promotion_detail, []);
            let promotion_length = 0;
            for (let index in promotion_detail) {
              promotion_length++;
            }
            that.setData({
              goods_info: goods_info,
              detail_id: detail_id,
              show_price: show_price,
              imgUrls: imgUrls,
              buy_num: buy_num,
              is_load: 1,
              promotion_length: promotion_length
            });

            //限时折扣计时
            if (goods_info.promotion_detail != undefined && goods_info.promotion_detail.discount_detail) {
              let time_array = {};
              time_array.end = 0;
              time_array.end_time = goods_info.promotion_detail.discount_detail.end_time;
              that.timing(that, time_array, 0);
            }

            //砍价计时
            if (goods_info.promotion_detail != undefined && goods_info.promotion_detail.bargain && bargain_id) {
              let time_array = {};
              time_array.end = 0;
              time_array.end_time = goods_info.promotion_detail.bargain.data.end_time;
              that.timing(that, time_array, 0);
            }

            //团购计时
            if (goods_info.promotion_detail != undefined && goods_info.promotion_detail.group_buy) {
              let time_array = {};
              time_array.end = 0;
              time_array.end_time = goods_info.promotion_detail.group_buy.data.end_time;
              that.timing(that, time_array, 0);
            }

            //规格组、库存判断
            let sku_info = that.data.sku_info; //选中规格信息
            let sku_id = that.data.sku_id; //选中规格
            let sku_pic = that.data.sku_pic; //规格图
            let spec_id = that.data.spec_id; //spu ID
            let spec_value_id = that.data.spec_value_id; //spu value ID
            let attr_value_items = that.data.attr_value_items; //规格组
            let stock = 0; //库存

            //规格默认选中
            for (let i = 0; i < goods_info.spec_list.length; i++) {
              for (let l = 0; l < goods_info.spec_list[i].value.length; l++) {
                if (attr_value_items[i] != undefined && attr_value_items[i] != '' && spec_id.length != 0 && spec_value_id.length != 0) {
                  if (attr_value_items[i] == goods_info.spec_list[i].value[l].spec_id + ':' + goods_info.spec_list[i].value[l].spec_value_id) {
                    goods_info.spec_list[i].value[l]['status'] = 1;
                  } else {
                    goods_info.spec_list[i].value[l]['status'] = 0;
                  }
                } else {
                  if (l == 0) {
                    goods_info.spec_list[i].value[l]['status'] = 1;
                    spec_id[i] = goods_info.spec_list[i].value[l].spec_id;
                    spec_value_id[i] = goods_info.spec_list[i].value[l].spec_value_id;
                    attr_value_items[i] = spec_id[i] + ':' + spec_value_id[i];
                    attr_value_items.length = i + 1;
                  } else {
                    goods_info.spec_list[i].value[l]['status'] = 0;
                  }
                }
              }
            }

            //规格组、库存判断
            for (let i = 0; i < goods_info.sku_list.length; i++) {
              let count = 1;

              for (let l = 0; l < attr_value_items.length; l++) {
                if (goods_info.sku_list[i].attr_value_items.indexOf(attr_value_items[l]) == -1) {
                  count = 0;
                }
              }
              if (count == 1) {
                attr_value_items_format = goods_info.sku_list[i].attr_value_items_format;
                sku_id = goods_info.sku_list[i].sku_id;
                member_price = goods_info.sku_list[i].member_price;
                let promote_price = goods_info.sku_list[i].promote_price;
                if (parseFloat(promote_price) < parseFloat(member_price)) {
                  member_price = promote_price;
                }
                stock = goods_info.sku_list[i].stock;
                sku_info = goods_info.sku_list[i];
                // 规格图处理
                if (goods_info.sku_list[i].sku_img_main != undefined && goods_info.sku_list[i].sku_img_main.pic_cover_mid != undefined) {
                  sku_pic.src = app.IMG(goods_info.sku_list[i].sku_img_main.pic_cover_mid);
                }
                if (app.checkArray(goods_info.sku_list[i].sku_img_list)) {
                  let img_list = [];
                  for (let index in goods_info.sku_list[i].sku_img_list) {
                    img_list[index] = app.IMG(goods_info.sku_list[i].sku_img_list[index].pic_cover_mid);
                  }
                  sku_pic.img_list = img_list;
                }
              }
            }

            that.setData({
              spec_list: goods_info.spec_list,
              sku_id: sku_id,
              sku_pic: sku_pic,
              attr_value_items_format: attr_value_items_format,
              member_price: member_price,
              stock: stock,
              sku_info: sku_info,
            })

            // 是否收藏
            that.whetherCollection();

            // 商家服务
            that.merchantService();

            // 加载评论统计
            that.getCommentsCount();

            // 加载评论列表
            that.getComments();

            // 加载地址信息
            if (goods_info.promotion_detail.bargain && bargain_id) {
              that.loadAddress();
            }
          } catch (error) {
            console.log(error)
            app.showModal({
              content: '商品信息加载失败...', //错误信息: error
              url: '/pages/index/index'
            })
          }
        } else {
          app.showBox(that, '商品信息加载失败...');
          setTimeout(function() {
            wx.navigateBack({
              delta: 1
            })
          }, 1200);
          //console.log(res.message);
        }
      }
    })

    that.joinTuan();
  },

  //获得拼团数据
  joinTuan: function() {
    let that = this;
    app.sendRequest({
      url: 'NsPintuan.Pintuan.pintuanList',
      data: {
        page_index: 1,
        page_size: 0,
        condition: 'goods_id=' + that.data.goods_id + ' and status=1',
        order: 'create_time desc'
      },
      success: function(res) {
        if (res.code == 0) {
          let pintuan_list = res.data.data;
          if (pintuan_list != undefined) {
            for (let index in pintuan_list) {
              let img = pintuan_list[index].group_user_head_img;
              pintuan_list[index].group_user_head_img = app.IMG(img);
            }
          }


          //拼团计时
          if (pintuan_list != undefined) {
            for (let index in pintuan_list) {
              let time_array = {};
              time_array.end = 0;
              time_array.end_time = pintuan_list[index].end_time;
              that.timing(that, time_array, index, false);
            }
          }
          that.setData({
            pintuan_list: pintuan_list
          })
        }
      }
    })
  },

  // 是否收藏
  whetherCollection: function() {
    let that = this;
    let goods_id = that.data.goods_id;

    app.sendRequest({
      url: 'System.Goods.whetherCollection',
      data: {
        fav_id: goods_id,
        fav_type: 'goods'
      },
      success: function(res) {
        let code = res.code;
        let data = res.data;
        if (code == 0) {
          that.setData({
            whether_collection: data
          })
        }
      }
    });
  },

  // 商家服务
  merchantService: function() {
    let that = this;
    let goods_id = that.data.goods_id;

    app.sendRequest({
      url: 'System.Config.merchantService',
      data: {
        goods_id: goods_id,
      },
      success: function(res) {
        let code = res.code;
        let data = res.data;
        if (code == 0) {
          let merchant_service_list = data;
          if (app.checkArray(merchant_service_list)) {
            for (let index in merchant_service_list) {
              merchant_service_list[index].pic = app.IMG(merchant_service_list[index].pic);
            }
          }
          that.setData({
            merchant_service_list: merchant_service_list
          })
        }
      }
    });
  },

  /**
   * 加载地址信息
   */
  loadAddress: function() {
    let that = this;
    // 收货地址
    app.sendRequest({
      url: 'System.Member.memberAddressList',
      data: {},
      success: function(res) {
        let code = res.code;
        let data = res.data;
        if (code == 0) {
          if (app.checkArray(data.data)) {
            let address_list = app.checkArray(data.data) ? data.data : [];

            for (let index in address_list) {
              address_list[index].address_info = address_list[index].address_info.replace(/&nbsp;/g, '　');
            }

            that.setData({
              address_list: address_list
            })
          }
        }
      }
    });
    // 自提地址
    app.sendRequest({
      url: 'System.Shop.pickupPointList',
      data: {},
      success: function(res) {
        let code = res.code;
        let data = res.data;
        if (code == 0) {
          if (app.checkArray(data.data)) {
            let pickup_list = app.checkArray(data.data) ? data.data : [];

            that.setData({
              pickup_list: pickup_list
            })
          }
        }
      }
    });
  },

  /**
   * 输入手机号
   */
  inputReceiverMobile: function(e) {
    let receiver_mobile = e.detail.value;
    this.setData({
      receiver_mobile: receiver_mobile
    })
  },

  /**
   * 图片加载失败
   */
  errorImg: function(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let goods_info = that.data.goods_info;
    let imgUrls = that.data.imgUrls;
    let default_img = that.data.default_img;
    let param = {};
    let img = imgUrls[index].pic_cover_mid;

    if (default_img.is_use == 1) {
      let default_goods_img = default_img.value.default_goods_img;

      if (img.indexOf(default_goods_img) == -1) {
        let param_key = "imgUrls[" + index + "].pic_cover_mid";
        param[param_key] = default_goods_img;
        param_key = "goods_info.img_list[0].pic_cover_micro";
        param[param_key] = default_goods_img;
        param_key = 'goods_info.img_list[0].pic_cover_mid';
        param[param_key] = default_goods_img;
        param_key = 'goods_info.img_list[0].pic_cover_small';
        param[param_key] = default_goods_img;
        that.setData(param);
      }
    }
  },

  /**
   * 组合套餐图片加载失败
   */
  errorComboImg: function(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let goods_info = that.data.goods_info;
    let default_img = that.data.default_img;
    let param = {};
    let img = goods_info.comboPackageGoodsArray.goods_array[index].pic_cover_micro;

    if (default_img.is_use == 1) {
      let default_img = default_img.value.default_goods_img;
      if (img.indexOf(default_img) == -1) {
        let param_key = "goods_info.comboPackageGoodsArray.goods_array[" + index + "].pic_cover_micro";

        param[param_key] = default_img;
        that.setData(param);
      }
    }
  },

  /**
   * 头像加载失败
   */
  errorHeadImg: function(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let comments_list = that.data.comments_list;
    let default_img = that.data.default_img;
    let param = {};
    let img = comments_list[index].user_img;

    if (default_img.is_use == 1) {
      let default_img = default_img.value.default_headimg;
      if (img.indexOf(default_img) == -1) {
        let param_key = "comments_list[" + index + "].user_img";

        param[param_key] = default_img;
        that.setData(param);
      }
    }
  },

  /**
   * 拼团用户头像加载失败
   */
  errorPintuanUserImg: function(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let pintuan = that.data.pintuan_list;
    let default_img = that.data.default_img;
    let key = e.currentTarget.dataset.key;
    let param = {};
    let param_key = "pintuan_list[" + index + "].group_user_head_img";
    let img = pintuan[index].group_user_head_img;

    if (default_img.is_use == 1) {
      let default_img = default_img.value.default_headimg;
      if (img.indexOf(default_img) == -1) {
        param[param_key] = default_img;
        that.setData(param);
      }
    }
  },

  /**
   * 组合商品详情
   */
  comboGoodsDetail: function(e) {
    let that = this;
    let dataset = e.currentTarget.dataset;
    let goods_id = dataset.id;
    let goods_name = dataset.name;
    let comboFlag = that.data.comboFlag;

    if (comboFlag == 1) {
      return false;
    }
    app.clicked(that, 'comboFlag');

    wx.redirectTo({
      url: '/pages/goods/goodsdetail/goodsdetail?goods_id=' + goods_id + '&goods_name=' + goods_name,
    })
  },

  /**
   * 组合套餐
   */
  comboPackages: function(e) {
    let that = this;
    let goods_id = e.currentTarget.dataset.id;
    let comboPackagesFlag = that.data.comboPackagesFlag;

    if (comboPackagesFlag == 1) {
      return false;
    }
    app.restStatus(that, 'comboPackagesFlag');

    wx.navigateTo({
      url: '/pages/goods/combopackagelist/combopackagelist?goods_id=' + goods_id,
    })
  },

  /**
   * 商品评论统计
   */
  getCommentsCount: function() {
    let that = this;
    let goods_id = that.data.goods_id;

    app.sendRequest({
      url: 'System.Goods.goodsEvaluateCount',
      data: {
        goods_id: goods_id,
      },
      success: function(res) {
        let code = res.code;
        let data = res.data;
        if (code == 0) {
          if (data) {
            let param = {};
            let key = 'goods_info.evaluates_count.evaluate_count';
            param[key] = data.evaluate_count;

            key = 'goods_info.evaluates_count.imgs_count';
            param[key] = data.imgs_count;

            key = 'goods_info.evaluates_count.praise_count';
            param[key] = data.praise_count;

            key = 'goods_info.evaluates_count.center_count';
            param[key] = data.center_count;

            key = 'goods_info.evaluates_count.bad_count';
            param[key] = data.bad_count;
            that.setData(param)
          }
        }
        //console.log(res)
      }
    });
  },

  /**
   * 商品评论
   */
  getComments: function(comment_type = 0) {
    let that = this;
    let comments_type = that.data.comments_type;
    let goods_id = that.data.goods_id;
    let default_img = that.data.default_img;

    app.sendRequest({
      url: 'System.Goods.goodsComments',
      data: {
        goods_id: goods_id,
        comments_type: comment_type,
        page_index: 1
      },
      success: function(res) {
        let code = res.code;
        let data = res.data;
        if (code == 0) {
          if (data.data.length > 0) {
            let comments_list = data.data;

            //头像处理
            comments_list[0].user_img = app.IMG(comments_list[0].user_img);
            if (comments_list[0].user_img == '') {
              if (default_img.is_use == 1) {
                default_img = default_img.value.default_headimg;
                comments_list[0].user_img = default_img;
              }
            }
            //匿名
            let new_member_name = '***';
            if (comments_list[0].member_name != '' && comments_list[0].member_name != undefined) {
              new_member_name = comments_list[0].member_name[0] + '***';
            }
            comments_list[0].member_name = comments_list[0].is_anonymous == 1 ? new_member_name : comments_list[0].member_name;

            //图片数组分割
            if (comments_list[0].image == '') {
              comments_list[0].image = {}
            } else {
              comments_list[0].image = comments_list[0].image.split(',');
              for (let key in comments_list[0].image) {
                let img = comments_list[0].image[key];
                comments_list[0].image[key] = app.IMG(img);
              }
            }
            if (comments_list[0].again_image == '') {
              comments_list[0].again_image = {}
            } else {
              comments_list[0].again_image = comments_list[0].again_image.split(',');
              for (let key in comments_list[0].again_image) {
                let img = comments_list[0].again_image[key];
                comments_list[0].again_image[key] = app.IMG(img);
              }
            }
            //时间戳转换
            if (comments_list[0].addtime > 0) {
              comments_list[0].addtime = time.formatTime(comments_list[0].addtime, 'Y-M-D h:m:s');
            }
            if (comments_list[0].again_addtime > 0) {
              comments_list[0].again_addtime = time.formatTime(comments_list[0].again_addtime, 'Y-M-D h:m:s');
            }

            that.setData({
              comments_list: comments_list,
              comments_type: comment_type,
            })
          } else {
            let comments_list = {};
            that.setData({
              comments_list: comments_list,
              comments_type: comment_type,
            })
          }
        }
        //console.log(res)
      }
    });
  },

  /**
   * 前去兑换（积分兑换）
   */
  integerExchange: function() {
    let goods_info = this.data.goods_info;
    let param = {};
    let key = 'goods_info.point_exchange_type';
    param[key] = 3;
    this.setData(param)
  },

  /**
   * 购买弹框(动画效果未实现)
   */
  sBuyShow: function(event) {
    let type = event.currentTarget.dataset.type;
    let status = 0;
    if (type == 'buy') {
      status = 0;
    } else if (type == 'addCart') {
      status = 1;
    } else if (type == 'group') {
      status = 3;
    } else if (type == 'js_point_exchange') {
      status = 5;
    } else if (type == 'goods_presell') {
      status = 6;
    } else if (type == 'bargain') {
      status = 7;
    }
    let animation = wx.createAnimation({
      duration: 500,
    })
    animation.bottom('0').step();
    this.animation = animation;
    this.setData({
      sBuy: 1,
      mask_show: 1,
      buyButtonStatus: status,
      animation: this.animation.export()
    })
  },

  /**
   * 关闭弹框
   */
  popupClose: function(event) {
    let that = this;
    let sBuy = that.data.sBuy;
    let poster_show = that.data.poster_show;

    if (sBuy == 1) {
      let animation = wx.createAnimation();
      animation.bottom('-100%').step();
      that.animation = animation;

      that.setData({
        animation: that.animation.export()
      })
    }
    let share_show = poster_show == 1 ? 1 : 0;
    let mask_show = poster_show == 1 ? 1 : 0;

    that.setData({
      sBuy: 0,
      popup_show: 0,
      service_show: 0,
      mask_show: mask_show,
      ladder_preferential_show: 0,
      spelling_show: 0,
      address_show: 0,
      goods_attr_show: 0,
      share_show: share_show,
      poster_show: 0
    })
  },

  /**
   * sku选中
   */
  skuSelect: function(event) {
    let that = this;
    let key = event.currentTarget.dataset.key;
    let k = event.currentTarget.dataset.k;
    let goods_info = that.data.goods_info;
    let arr = that.data.spec_list;
    let stock = that.data.stock;
    let sku_id = that.data.sku_id;
    let attr_value_items_format = that.data.attr_value_items_format;
    let member_price = that.data.member_price;
    let attr_value_items = {};
    let sku_info = that.data.sku_info;
    let sku_pic = that.data.sku_pic;
    let spec_id = that.data.spec_id;
    let spec_value_id = that.data.spec_value_id;

    for (let i = 0; i < arr[key].value.length; i++) {
      arr[key].value[i].status = 0;
    }
    arr[key].value[k].status = 1;
    //拼合规格组
    for (let i = 0; i < arr.length; i++) {
      for (let l = 0; l < arr[i].value.length; l++) {
        if (arr[i].value[l]['status'] == 1) {
          spec_id[i] = arr[i].value[l].spec_id;
          spec_value_id[i] = arr[i].value[l].spec_value_id;
          attr_value_items[i] = spec_id[i] + ':' + spec_value_id[i];
          attr_value_items.length = i + 1;
        }
      }
    }

    //规格组、库存判断
    for (let i = 0; i < goods_info.sku_list.length; i++) {
      let count = 1;
      for (let l = 0; l < attr_value_items.length; l++) {
        if (goods_info.sku_list[i].attr_value_items.indexOf(attr_value_items[l]) == -1) {
          count = 0;
        }
      }
      if (count == 1) {
        sku_id = goods_info.sku_list[i].sku_id;
        attr_value_items_format = goods_info.sku_list[i].attr_value_items_format;
        member_price = goods_info.sku_list[i].member_price;
        let promote_price = goods_info.sku_list[i].promote_price;
        if (parseFloat(promote_price) < parseFloat(member_price)) {
          member_price = promote_price;
        }
        stock = goods_info.sku_list[i].stock;
        sku_info = goods_info.sku_list[i];
        // 规格图处理
        if (goods_info.sku_list[i].sku_img_main != undefined && goods_info.sku_list[i].sku_img_main.pic_cover_mid != undefined) {
          sku_pic.src = app.IMG(goods_info.sku_list[i].sku_img_main.pic_cover_mid);
        }
        if (app.checkArray(goods_info.sku_list[i].sku_img_list)) {
          let img_list = [];
          for (let index in goods_info.sku_list[i].sku_img_list) {
            img_list[index] = app.IMG(goods_info.sku_list[i].sku_img_list[index].pic_cover_mid);
          }
          sku_pic.img_list = img_list;
        }
      }
    }

    that.setData({
      spec_list: arr,
      sku_id: sku_id,
      spec_id: spec_id,
      spec_value_id: spec_value_id,
      attr_value_items: attr_value_items,
      attr_value_items_format: attr_value_items_format,
      member_price: member_price,
      stock: stock,
      sku_info: sku_info,
      sku_pic: sku_pic
    })
  },

  /**
   * 商品数量调节
   */
  buy_numAdjust: function(event) {
    let that = this;
    let button_type = event.currentTarget.dataset.type;
    let num = parseInt(that.data.buy_num);
    let numCount = parseInt(that.data.stock);
    let max_buy = parseInt(that.data.goods_info.max_buy);
    let min_buy = parseInt(that.data.goods_info.min_buy);

    if (button_type == 'add' && numCount > 0) {
      num++;
      if (max_buy > 0 && num > max_buy) {
        app.showBox(that, '此商品限购，您最多购买' + max_buy + '件');
        return false;
      }

      if (num > numCount) {
        num = numCount;
      }
    } else if (button_type == 'minus' && numCount > 0) {
      num--;
      if (min_buy > 0 && num < min_buy) {
        app.showBox(that, '此商品限购，您最少购买' + min_buy + '件');
        return false;
      }

      if (num <= 0) {
        num = 1;
      }
    } else {
      num = 1;
    }
    that.setData({
      buy_num: num
    })
  },

  /**
   * 数量调节检测
   */
  buy_numAdjustCheck: function(event) {
    let that = this;
    let num = event.detail.value;
    let numCount = parseInt(that.data.stock);
    let max_buy = parseInt(that.data.goods_info.max_buy);
    let min_buy = parseInt(that.data.goods_info.min_buy);

    if (max_buy > 0 && num > max_buy) {
      app.showBox(that, '此商品限购，您最多购买' + max_buy + '件');
      that.setData({
        buy_num: max_buy
      })
      return;
    }

    if (min_buy > 0 && num < min_buy) {
      app.showBox(that, '此商品限购，您最少购买' + min_buy + '件');
      that.setData({
        buy_num: min_buy
      })
      return;
    }

    if (num > numCount) {
      num = numCount;
    } else if (num < 0) {
      num = 0;
    }
    that.setData({
      buy_num: num
    })
  },

  /**
   * 加入购物车
   */
  addCart: function(event) {
    let that = this;
    let addCartFlag = that.data.addCartFlag;
    let goods_info = that.data.goods_info;
    let purchase_num = goods_info.purchase_num;
    let count = that.data.buy_num;

    if (addCartFlag == 1) {
      return false;
    }
    app.clicked(that, 'addCartFlag');

    if (goods_info.state == 0) {
      app.showBox(that, '该商品已下架');
      app.restStatus(that, 'addCartFlag');
      return false;
    }

    if (goods_info.state == 10) {
      app.showBox(that, '该商品属于违禁商品，现已下架');
      app.restStatus(that, 'addCartFlag');
      return false;
    }
    let cart_detail = {
      shop_name: 'Niushop开源商城',
      goods_id: that.data.goods_info.goods_id,
      goods_name: that.data.goods_info.goods_name,
      count: count,
      sku_id: that.data.sku_id,
      sku_name: that.data.sku_info.sku_name,
      price: that.data.sku_info.price,
      picture_id: that.data.goods_info.picture
    };
    cart_detail = JSON.stringify(cart_detail);

    app.sendRequest({
      url: 'System.Goods.addCart',
      data: {
        cart_detail: cart_detail,
      },
      success: function(res) {
        let code = res.code;
        let data = res.data;
        if (code == 0) {
          if (data.code > 0) {
            app.showBox(that, '加入购物车成功')
            purchase_num = parseInt(purchase_num) + parseInt(count);
            let d = {};
            let param = "goods_info.cart_count";
            d[param] = purchase_num;

            that.setData(d);
            that.popupClose();
            app.restStatus(that, 'addCartFlag');
          } else {
            app.showBox(that, data.message)
            app.restStatus(that, 'addCartFlag');
          }
        }
      }
    });
  },

  /**
   * 购买下一步
   */
  buyNext: function(event) {
    let that = this;
    let sku_id = that.data.sku_id;
    let stock = that.data.stock;
    let goods_num = parseInt(that.data.buy_num);
    let goods_sku_list = '';
    let goods_info = that.data.goods_info;
    let purchase_num = parseInt(goods_info.purchase_num);
    let max_buy = parseInt(goods_info.max_buy);
    let min_buy = parseInt(goods_info.min_buy);
    let buyNextFlag = that.data.buyNextFlag;

    if (buyNextFlag == 1) {
      return false;
    }
    app.clicked(that, 'buyNextFlag');

    if (goods_info.state == 0) {
      app.showBox(that, '该商品已下架');
      app.restStatus(that, 'buyNextFlag');
      return false;
    }

    if (goods_info.state == 10) {
      app.showBox(that, '该商品属于违禁商品，现已下架');
      app.restStatus(that, 'buyNextFlag');
      return false;
    }

    if (stock <= 0) {
      app.showBox(that, '商品已售馨');
      app.restStatus(that, 'buyNextFlag');
      return false;
    }

    if (goods_num <= 0) {
      app.showBox(that, '最少购买1件商品');
      app.restStatus(that, 'buyNextFlag');
      return false;
    }

    if (max_buy > 0 && (purchase_num + goods_num) > max_buy) {
      app.showBox(that, '此商品限购，您最多购买' + max_buy + '件');
      app.restStatus(that, 'buyNextFlag');
      return false;
    }
    let tag = "buy_now";
    let sku_list = sku_id + ':' + goods_num;

    wx.navigateTo({
      url: '/pagesother/pages/order/paymentorder/paymentorder?order_type=1&sku=' + sku_list,
    })
  },

  /**
   * 发起拼团
   */
  groupBooking: function(e) {
    let that = this;
    let sku_id = that.data.sku_id;
    let stock = that.data.stock;
    let goods_num = parseInt(that.data.buy_num);
    let goods_sku_list = '';
    let goods_info = that.data.goods_info;
    let purchase_num = parseInt(goods_info.purchase_num);
    let max_buy = parseInt(goods_info.max_buy);
    let min_buy = parseInt(goods_info.min_buy);
    let groupBookingFlag = that.data.groupBookingFlag;

    if (groupBookingFlag == 1) {
      return false;
    }
    app.clicked(that, 'groupBookingFlag');

    if (goods_info.state == 0) {
      app.showBox(that, '该商品已下架');
      app.restStatus(that, 'groupBookingFlag');
      return false;
    }

    if (goods_info.state == 10) {
      app.showBox(that, '该商品属于违禁商品，现已下架');
      app.restStatus(that, 'groupBookingFlag');
      return false;
    }

    if (stock <= 0) {
      app.showBox(that, '商品已售馨');
      app.restStatus(that, 'groupBookingFlag');
      return false;
    }

    if (goods_num <= 0) {
      app.showBox(that, '最少购买1件商品');
      app.restStatus(that, 'groupBookingFlag');
      return false;
    }

    if (max_buy > 0 && (purchase_num + goods_num) > max_buy) {
      app.showBox(that, '此商品限购，您最多购买' + max_buy + '件');
      app.restStatus(that, 'groupBookingFlag');
      return false;
    }
    let sku_list = sku_id + ':' + goods_num;
    let goods_type = goods_info.goods_type;

    wx.navigateTo({
      url: '/pagesother/pages/order/paymentorder/paymentorder?order_type=4&sku=' + sku_list,
    })
  },

  /**
   * 空库存
   */
  nullStock: function() {
    let that = this;
    app.showBox(that, '商品已售馨');
  },

  /**
   * 收藏
   */
  collection: function() {
    let that = this;
    let goods_info = that.data.goods_info;
    let whether_collection = that.data.whether_collection;
    let method = whether_collection == 0 ? 'addCollection' : 'cancelCollection';
    let message = whether_collection == 0 ? '收藏' : '取消收藏';
    whether_collection = whether_collection == 0 ? 1 : 0;
    let param = {
      fav_id: goods_info.goods_id,
      fav_type: 'goods',
    }

    if (method == 'addCollection') {
      param.log_msg = goods_info.goods_name;
    }

    app.sendRequest({
      url: 'System.Member.' + method,
      data: param,
      success: function(res) {
        let code = res.code;
        let data = res.data;
        if (code == 0) {
          if (data > 0) {
            app.showBox(that, message + '成功');

            that.setData({
              whether_collection: whether_collection
            })
          } else {
            app.showBox(that, message + '失败');
          }
        }
      }
    });
  },

  /**
   * 去团购
   */
  groupPurchase: function(e) {
    let that = this;
    let groupPurchaseFlag = that.data.groupPurchaseFlag;
    let goods_id = e.currentTarget.dataset.id;
    let goods_name = e.currentTarget.dataset.name;

    if (groupPurchaseFlag == 1) {
      return false;
    }
    app.clicked(that, 'groupPurchaseFlag');

    wx.navigateTo({
      url: '/pages/goods/grouppurchase/grouppurchase?goods_id=' + goods_id + '&goods_name=' + goods_name,
    })
  },

  /**
   * 去拼单
   */
  spellList: function(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let spelling = that.data.pintuan_list[index];
    spelling.index = index;

    that.setData({
      spelling: spelling,
      spelling_show: 1,
      mask_show: 1,
    })
  },

  /**
   * 参与拼单
   */
  participateSpellList: function(e) {
    let that = this;
    let group_id = e.currentTarget.dataset.id;

    that.popupClose();

    let status = 4;
    let animation = wx.createAnimation({
      duration: 500,
    })
    animation.bottom('0').step();
    this.animation = animation;
    this.setData({
      sBuy: 1,
      mask_show: 1,
      buyButtonStatus: status,
      group_id: group_id,
      animation: this.animation.export()
    })
  },

  /**
   * 确认拼单
   */
  confirmSpellingList: function(e) {
    let that = this;
    let sku_id = that.data.sku_id;
    let group_id = that.data.group_id;
    let stock = that.data.stock;
    let goods_num = parseInt(that.data.buy_num);
    let goods_sku_list = '';
    let goods_info = that.data.goods_info;
    let purchase_num = parseInt(goods_info.purchase_num);
    let max_buy = parseInt(goods_info.max_buy);
    let min_buy = parseInt(goods_info.min_buy);
    let confirmSpellFlag = that.data.confirmSpellFlag;

    if (confirmSpellFlag == 1) {
      return false;
    }
    app.clicked(that, 'confirmSpellFlag');

    if (goods_info.state == 0) {
      app.showBox(that, '该商品已下架');
      app.restStatus(that, 'confirmSpellFlag');
      return false;
    }

    if (goods_info.state == 10) {
      app.showBox(that, '该商品属于违禁商品，现已下架');
      app.restStatus(that, 'confirmSpellFlag');
      return false;
    }

    if (stock <= 0) {
      app.showBox(that, '商品已售馨');
      app.restStatus(that, 'confirmSpellFlag');
      return false;
    }

    if (goods_num <= 0) {
      app.showBox(that, '最少购买1件商品');
      app.restStatus(that, 'confirmSpellFlag');
      return false;
    }

    if (max_buy > 0 && (purchase_num + goods_num) > max_buy) {
      app.showBox(that, '此商品限购，您最多购买' + max_buy + '件');
      app.restStatus(that, 'confirmSpellFlag');
      return false;
    }
    let sku_list = sku_id + ':' + goods_num;

    wx.navigateTo({
      url: '/pagesother/pages/order/paymentorder/paymentorder?order_type=4&sku=' + sku_list + '&group_id=' + group_id,
    })
  },

  /**
   * 积分兑换
   */
  pointExchange: function(e) {
    let that = this;
    let sku_id = that.data.sku_id;
    let stock = that.data.stock;
    let goods_num = parseInt(that.data.buy_num);
    let goods_sku_list = '';
    let goods_info = that.data.goods_info;
    let purchase_num = parseInt(goods_info.purchase_num);
    let max_buy = parseInt(goods_info.max_buy);
    let min_buy = parseInt(goods_info.min_buy);
    let pointExchangeFlag = that.data.pointExchangeFlag;

    if (pointExchangeFlag == 1) {
      return false;
    }
    app.clicked(that, 'pointExchangeFlag');

    if (goods_info.state == 0) {
      app.showBox(that, '该商品已下架');
      app.restStatus(that, 'pointExchangeFlag');
      return false;
    }

    if (goods_info.state == 10) {
      app.showBox(that, '该商品属于违禁商品，现已下架');
      app.restStatus(that, 'pointExchangeFlag');
      return false;
    }

    if (stock <= 0) {
      app.showBox(that, '商品已售馨');
      app.restStatus(that, 'pointExchangeFlag');
      return false;
    }

    if (goods_num <= 0) {
      app.showBox(that, '最少购买1件商品');
      app.restStatus(that, 'pointExchangeFlag');
      return false;
    }

    if (max_buy > 0 && (purchase_num + goods_num) > max_buy) {
      app.showBox(that, '此商品限购，您最多购买' + max_buy + '件');
      app.restStatus(that, 'pointExchangeFlag');
      return false;
    }
    let sku_list = sku_id + ':' + goods_num;

    wx.navigateTo({
      url: '/pagesother/pages/order/paymentorder/paymentorder?order_type=1&promotion_type=4&sku=' + sku_list,
    })
  },

  /**
   * 立即预定
   */
  goodsPresell: function(e) {
    let that = this;
    let sku_id = that.data.sku_id;
    let stock = that.data.stock;
    let goods_num = parseInt(that.data.buy_num);
    let goods_sku_list = '';
    let goods_info = that.data.goods_info;
    let purchase_num = parseInt(goods_info.purchase_num);
    let max_buy = parseInt(goods_info.max_buy);
    let min_buy = parseInt(goods_info.min_buy);
    let goodsPresellFlag = that.data.goodsPresellFlag;

    if (goodsPresellFlag == 1) {
      return false;
    }
    app.clicked(that, 'goodsPresellFlag');

    if (goods_info.state == 0) {
      app.showBox(that, '该商品已下架');
      app.restStatus(that, 'goodsPresellFlag');
      return false;
    }

    if (goods_info.state == 10) {
      app.showBox(that, '该商品属于违禁商品，现已下架');
      app.restStatus(that, 'goodsPresellFlag');
      return false;
    }

    if (stock <= 0) {
      app.showBox(that, '商品已售馨');
      app.restStatus(that, 'goodsPresellFlag');
      return false;
    }

    if (goods_num <= 0) {
      app.showBox(that, '最少购买1件商品');
      app.restStatus(that, 'goodsPresellFlag');
      return false;
    }

    if (max_buy > 0 && (purchase_num + goods_num) > max_buy) {
      app.showBox(that, '此商品限购，您最多购买' + max_buy + '件');
      app.restStatus(that, 'goodsPresellFlag');
      return false;
    }
    let sku_list = sku_id + ':' + goods_num;
    let goods_type = goods_info.goods_type;
    let point_exchange_type = goods_info.point_exchange_type;
    let promotion_type = 0;
    if (point_exchange_type == 1 || point_exchange_type == 3) {
      promotion_type = 4;
    }

    wx.navigateTo({
      url: '/pagesother/pages/order/paymentorder/paymentorder?order_type=6&sku=' + sku_list + '&promotion_type=' + promotion_type,
    })
  },

  /**
   * 选择评论类型
   */
  evaluationType: function(e) {
    let that = this;
    let goods_id = that.data.goods_id;
    let evaluation_type = e.currentTarget.dataset.type;

    that.getComments(evaluation_type);
  },

  /**
   * 更多评论
   */
  moreEvaluation: function(e) {
    let that = this;
    let goods_id = that.data.goods_id;
    let evaluation_type = e.currentTarget.dataset.type;
    let moreEvaluationFlag = that.data.moreEvaluationFlag;

    if (moreEvaluationFlag == 1) {
      return false;
    }
    app.clicked(that, 'moreEvaluationFlag');

    wx.navigateTo({
      url: '/pages/goods/controlevaluation/controlevaluation?id=' + goods_id + '&type=' + evaluation_type
    })
  },

  /**
   * 显示商家服务
   */
  serviceShow: function(e) {
    let that = this;

    that.setData({
      service_show: 1,
      mask_show: 1
    })
  },

  /**
   * 显示阶梯优惠
   */
  ladderPreferentialShow: function() {
    let that = this;
    that.setData({
      ladder_preferential_show: 1,
      mask_show: 1,
    })
  },

  /**
   * 显示优惠券
   */
  popupShow: function(e) {
    let that = this;

    that.setData({
      popup_show: 1,
      mask_show: 1
    })
  },

  /**
   * 商品数量调节
   */
  goodsNumAdjust: function(event) {
    let that = this;
    let button_type = event.currentTarget.dataset.type;
    let num = parseInt(that.data.buy_num);
    let numCount = parseInt(that.data.stock);
    let max_buy = parseInt(that.data.goods_info.max_buy);
    let min_buy = parseInt(that.data.goods_info.min_buy);

    if (button_type == 'add' && numCount > 0) {
      num++;
      if (max_buy > 0 && num > max_buy) {
        app.showBox(that, '此商品限购，您最多购买' + max_buy + '件');
        return false;
      }

      if (num > numCount) {
        num = numCount;
      }
    } else if (button_type == 'minus' && numCount > 0) {
      num--;
      if (min_buy > 0 && num < min_buy) {
        app.showBox(that, '此商品限购，您最少购买' + min_buy + '件');
        return false;
      }

      if (num <= 0) {
        num = 1;
      }
    } else {
      num = 1;
    }
    that.setData({
      buy_num: num
    })
  },
  /**
   * 数量调节检测
   */
  goodsNumAdjustCheck: function(event) {
    let that = this;
    let num = event.detail.value;
    let numCount = parseInt(that.data.stock);
    let max_buy = parseInt(that.data.goods_info.max_buy);
    let min_buy = parseInt(that.data.goods_info.min_buy);

    if (max_buy > 0 && num > max_buy) {
      app.showBox(that, '此商品限购，您最多购买' + max_buy + '件');
      that.setData({
        buy_num: max_buy
      })
      return;
    }

    if (min_buy > 0 && num < min_buy) {
      app.showBox(that, '此商品限购，您最少购买' + min_buy + '件');
      that.setData({
        buy_num: min_buy
      })
      return;
    }

    if (num > numCount) {
      num = numCount;
    } else if (num < 0) {
      num = 0;
    }
    that.setData({
      buy_num: num
    })
  },

  /**
   * 领取优惠券
   */
  toReceivePopup: function(e) {
    let that = this;
    let coupon_type_id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    let max_fetch = parseInt(e.currentTarget.dataset.fetch);
    let receive_quantity = parseInt(e.currentTarget.dataset.quantity);
    let toReceivePopupFlag = that.data.toReceivePopupFlag;

    if (max_fetch > 0 && receive_quantity >= max_fetch) {
      app.showBox(that, '领取已达到上限');
    }
    if (toReceivePopupFlag) {
      return false;
    }
    app.clicked(that, 'toReceivePopupFlag');

    app.sendRequest({
      url: 'System.Goods.receiveGoodsCoupon',
      data: {
        coupon_type_id: coupon_type_id,
        scenario_type: 3
      },
      success: function(res) {
        let code = res.code;
        let data = res.data;

        if (code == 0) {
          app.restStatus(that, 'toReceivePopupFlag');
          if (data > 0) {
            app.showBox(that, '领取成功');
          } else {
            if (data == -2010) {
              app.showBox(that, "领取已达到上限");
            } else if (data == -2011) {
              app.showBox(that, '来迟了，已经领完了');
            } else if (data == -2019) {
              app.showBox(that, '领取已达到上限');
            } else {
              app.showBox(that, '未获取到优惠券信息');
            }
            return false;
          }
          receive_quantity++;
          let d = {};
          let key = "goods_info.goods_coupon_list[" + index + "].receive_quantity";
          d[key] = receive_quantity;

          that.setData(d);
        }
      }
    });
  },

  /**
   * 计时(数组形式)
   */
  timing: function(that, timer_array, index, has_day = true) {
    let current_time = that.data.current_time;
    let count_second = (timer_array.end_time - current_time);
    let d = {};
    let param = '';

    //首次加载
    if (count_second > 0) {
      count_second--;
      //时间计算
      let day = has_day ? Math.floor((count_second / 3600) / 24) : null;
      let hour = has_day ? Math.floor((count_second / 3600) % 24) : Math.floor(count_second / 3600);
      let minute = Math.floor((count_second / 60) % 60);
      let second = Math.floor(count_second % 60);

      hour = hour < 10 ? '0' + hour : hour;
      minute = minute < 10 ? '0' + minute : minute;
      second = second < 10 ? '0' + second : second;

      //赋值
      timer_array.day = has_day ? day : null;
      timer_array.hour = hour;
      timer_array.minute = minute;
      timer_array.second = second;
      timer_array.end = 0;

      d = {};
      param = 'timer_array[' + index + ']';
      d[param] = timer_array;
      that.setData(d);
    } else {
      timer_array.end = 1;

      d = {};
      param = 'timer_array[' + index + ']';
      d[param] = timer_array;
      that.setData(d);
    }
    //开始计时
    let timer = setInterval(function() {
      if (count_second > 0) {
        count_second--;
        //时间计算
        let day = has_day ? Math.floor((count_second / 3600) / 24) : null;
        let hour = has_day ? Math.floor((count_second / 3600) % 24) : Math.floor(count_second / 3600);
        let minute = Math.floor((count_second / 60) % 60);
        let second = Math.floor(count_second % 60);

        hour = hour < 10 ? '0' + hour : hour;
        minute = minute < 10 ? '0' + minute : minute;
        second = second < 10 ? '0' + second : second;

        //赋值
        timer_array.day = has_day ? day : null;
        timer_array.hour = hour;
        timer_array.minute = minute;
        timer_array.second = second;
        timer_array.end = 0;

        d = {};
        param = 'timer_array[' + index + ']';
        d[param] = timer_array;
        that.setData(d);
      } else {
        timer_array.end = 1;

        d = {};
        param = 'timer_array[' + index + ']';
        d[param] = timer_array;
        param = 'timer_array[' + index + '].timer';
        d[param] = null;
        that.setData(d);

        clearInterval(timer);
      }
    }, 1000)
    d = {};
    param = 'timer_array[' + index + '].timer';
    d[param] = timer;
    that.setData(d);
  },

  /**
   * 图片预览
   */
  preivewImg: function(e) {
    let imgUrls = this.data.imgUrls;
    let index = e.currentTarget.dataset.index;
    let urls = [];
    for (let key in imgUrls) {
      urls.push(imgUrls[key].pic_cover_mid);
    }

    wx.previewImage({
      current: urls[index],
      urls: urls,
    })
  },

  /**
   * 规格图预览
   */
  preivewSkuImg: function(e) {
    let sku_pic = this.data.sku_pic;
    //console.log(sku_pic.img_list);
    if (sku_pic.img_list[0] != undefined) {
      wx.previewImage({
        current: sku_pic.img_list[0],
        urls: sku_pic.img_list,
      })
    }
  },

  /**
   * 选择显示类型
   */
  selectType: function(e) {
    let selectType = e.currentTarget.dataset.type;
    this.setData({
      selectType: selectType
    })
  },

  /**
   * 显示地址
   */
  addressShow: function(e) {
    this.setData({
      address_show: 1,
      mask_show: 1
    })
  },

  /**
   * 属性框弹出
   */
  goodsAttrShow: function(e) {
    this.setData({
      goods_attr_show: 1,
      mask_show: 1
    })
  },

  /**
   * 显示分享选项
   */
  shareShow: function() {
    this.setData({
      share_show: 1,
      mask_show: 1
    })
  },

  /**
   * 显示分享海报
   */
  posterShow: function() {
    this.loadPoster();
    this.setData({
      poster_show: 1,
      mask_show: 1
    })
  },

  /**
   * 选择配送方式
   */
  chooseDeliveryType: function(e) {
    let distribution_type = e.currentTarget.dataset.type;
    this.setData({
      distribution_type: distribution_type
    })
  },

  /**
   * 发起砍价
   */
  addBargainLaunch: function(e) {

    let that = this;
    let dataset = e.currentTarget.dataset;
    let distribution_type = dataset.type;
    let bargain_id = that.data.bargain_id;
    let sku_id = that.data.sku_id;
    let num = that.data.buy_num;

    let param = {
      sku_id: sku_id,
      num: num,
      bargain_id: bargain_id,
      distribution_type: distribution_type
    };

    if (distribution_type == 'virtual') {
      // 虚拟商品
      let receiver_mobile = that.data.receiver_mobile;
      if (!app.getRegex('mobile')) {
        app.showBox(that, '请输入正确的手机号');
        return false;
      }
      param.receiver_mobile = receiver_mobile;
    } else {
      // 实物商品
      param.address_id = dataset.id;
    }

    let bargainFlag = that.data.bargainFlag;
    if (bargainFlag == 1) {
      return false;
    }
    app.clicked(that, 'bargainFlag');
    that.getGoodsPurchaseRestrictionForCurrentUser('addBargainLaunchAction', param);
  },

  /**
   * 发起砍价
   */
  addBargainLaunchAction: function(param) {
    let that = this;

    app.sendRequest({
      url: 'NsBargain.Bargain.addBargain',
      data: param,
      success: function(res) {
        let code = res.code;
        let data = res.data;
        if (code == 0) {
          if (data.launch_id > 0) {
            wx.navigateTo({
              url: '/pagesother/pages/bargain/bargainlaunch/bargainlaunch?launch_id=' + data.launch_id,
            })
            setTimeout(function() {

            }, 1700);
          } else {
            app.restStatus(that, 'bargainFlag');
            app.showBox(that, '发起砍价失败');
          }

        } else {
          app.restStatus(that, 'bargainFlag');
          app.showBox(that, '发起砍价失败');
        }
      }
    });
  },

  /**
   * 检查商品限购
   */
  getGoodsPurchaseRestrictionForCurrentUser: function(callBack = null, param = null) {
    let that = this;
    let goods_id = that.data.goods_id;
    let num = that.data.buy_num;

    app.sendRequest({
      url: 'System.Goods.goodsPurchaseRestriction',
      data: {
        goods_id: goods_id,
        num: num
      },
      success: function(res) {
        let code = res.code;
        let data = res.data;
        if (code == 0) {
          if (callBack == 'addBargainLaunchAction') {
            that.addBargainLaunchAction(param);
          }
        } else {
          showBox(that, res.message);
          if (callBack == 'addBargainLaunchAction') {
            app.restStatus(that, 'bargainFlag');
          }
        }
      }
    });
  },

  bargainNext: function(e) {
    let that = this;
    let sku_id = that.data.sku_id;
    let stock = that.data.stock;
    let goods_num = 1;
    let goods_sku_list = '';
    let goods_info = that.data.goods_info;
    let purchase_num = parseInt(goods_info.purchase_num);
    let max_buy = parseInt(goods_info.max_buy);
    let min_buy = parseInt(goods_info.min_buy);
    let bargainNextFlag = that.data.bargainNextFlag;
    let member_price = that.data.member_price;
    if (bargainNextFlag == 1) {
      return false;
    }

    if (goods_info.state == 0) {
      app.showBox(that, '该商品已下架');
      app.restStatus(that, 'bargainNextFlag');
      return false;
    }

    if (goods_info.state == 10) {
      app.showBox(that, '该商品属于违禁商品，现已下架');
      app.restStatus(that, 'bargainNextFlag');
      return false;
    }

    if (stock <= 0) {
      app.showBox(that, '商品已售馨');
      app.restStatus(that, 'bargainNextFlag');
      return false;
    }

    if (member_price < 1) {
      app.showBox(that, '1元以下商品不能参加砍价活动');
      app.restStatus(that, 'bargainNextFlag');
      return false;
    }

    if (goods_num <= 0) {
      app.showBox(that, '最少购买1件商品');
      app.restStatus(that, 'bargainNextFlag');
      return false;
    }

    if (goods_num > 1) {
      app.showBox(that, '最多购买1件商品');
      app.restStatus(that, 'bargainNextFlag');
      return false;
    }

    let sku_list = sku_id + ':' + goods_num;
    let goods_type = goods_info.goods_type;
    that.popupClose();
    that.addressShow();
  },

  newAddress: function(e) {
    let that = this;
    let is_login = app.globalData.is_login;
    if (is_login == 0) {
      //未登录执行isNotLogin(code);
      app.isNotLogin('-9999');
      //未登录
      wx.showModal({
        title: '提示',
        content: '未登录 !',
        showCancel: false,
        success: function(res) {
          wx.reLaunch({
            url: '/pages/member/member/member',
          })
        }
      });
      return;
    }
    let dataset = e.currentTarget.dataset;
    let goods_id = dataset.id;
    let goods_name = dataset.name;
    let bargain_id = dataset.bargain_id;
    wx.navigateTo({
      url: '/pages/member/addmemberaddress/addmemberaddress?goods_id=' + goods_id + '&goods_name=' + goods_name + '&bargain_id=' + bargain_id,
    })
  },

  /**
   * 加载海报
   */
  loadPoster: function() {
    let that = this;
    let goods_id = that.data.goods_id;
    app.sendRequest({
      url: 'System.Goods.getGoodsPoster',
      data: {
        goods_id: goods_id,
      },
      success: function(res) {
        if (res.code == 0) {
          let poster_img = app.checkEmpty(res.data.path, '');
          poster_img = app.IMG(poster_img);

          that.setData({
            poster_img: poster_img
          });
        } else {
          app.showBox(that, res.message, 3000);
        }
      }
    });
  },

  /**
   * 预览海报
   */
  previewPoster: function() {
    let poster_img = this.data.poster_img;
    wx.previewImage({
      urls: [poster_img],
    })
  },

  /**
   * 保存图片
   */
  saveImg: function() {
    let that = this;
    let poster_img = this.data.poster_img;
    wx.getSetting({
      success: function(res) {
        if (res.authSetting['scope.writePhotosAlbum'] === false) {
          that.setData({
            save_img_open_type: 'openSetting'
          })
          app.showBox(that, '保存失败，请再次点击保存图片，并开启保存到相册权限', 6000);
          return;
        } else if (res.authSetting['scope.writePhotosAlbum'] === true) {
          that.setData({
            save_img_open_type: ''
          })
        }
      }
    });
    wx.downloadFile({
      url: poster_img,
      success: function(d_res) {
        if (d_res.tempFilePath) {
          poster_img = d_res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: poster_img,
          })
        }
      }
    })
  }
})